package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealDishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    public void addSetmeal(SetmealDto setmealDto) {
        //保存套餐数据到setmeal表中
        setmealMapper.insert(setmealDto);

        //获取当前套餐菜品列表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

        //循环遍历,获取每一个套餐菜品数据
        List<SetmealDish> list = setmealDishes.stream().map((item) -> {
            SetmealDish setmealDish = new SetmealDish();
            BeanUtils.copyProperties(item, setmealDish);
            //获取每一个套餐id
            Long setmealId = setmealDto.getId();
            setmealDish.setSetmealId(setmealId);
            return setmealDish;
        }).collect(Collectors.toList());

        //保存套餐菜品数据到setmeal_dish表中
        setmealDishService.saveBatch(list);
    }

    @Override
    public void updateSetmeal(SetmealDto setmealDto) {
        //根据id更新setmeal套餐表数据
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper();
        qw.in(setmealDto != null, Setmeal::getId, setmealDto.getId());
        setmealMapper.update(setmealDto, qw);

        //操作套餐对应的菜品数据
        // LambdaQueryWrapper<SetmealDish> qwd = new LambdaQueryWrapper<>();
        // qwd.in(setmealDto!=null,SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishMapper.deleteById(setmealDto.getId());

        //重新添加新的套餐对应的菜品数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = setmealDishes.stream().map((item) -> {
            //  SetmealDto setmealdto = new SetmealDto();
            Long id = setmealDto.getId();
            item.setSetmealId(id);
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);
    }
}
